package com.weixin.web;

import com.agent.entity.Knowledge;
import com.agent.entity.PicWord;
import com.agent.service.IKnowledgeService;
import com.agent.util.CommonUtils;
import com.agent.util.ResponseData;
import com.agent.vo.ConditionCount;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller("KnowledgeControllerForWeixin")
@RequestMapping("/weixin/knowledge")
public class KnowledgeController {
    private static Logger log = LoggerFactory.getLogger(KnowledgeController.class);
    @Autowired
    private IKnowledgeService knowledgeService;

    @RequestMapping(value = "/condition",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getCondition(){
        Map<String, Object> result = ResponseData.getSuccessResult();
        List<ConditionCount> condition = knowledgeService.getCondition();
        result.put(ResponseData.DATA,condition);
        return result;
    }


    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getKnowledgeList(@RequestParam("condition") String condition, Model model) {
        Map<String, Object> result = ResponseData.getSuccessResult();
        Map<String, List> map = new HashMap();
//        if (!StringUtils.isEmpty(condition)) {
            Knowledge knowledge = new Knowledge();
            String decode_condition = CommonUtils.encodeStr(condition);
            knowledge.setTag(decode_condition);
            knowledge.setTitle(decode_condition);
            List<Knowledge> list = knowledgeService
                    .searchKnowledgeByWeixin(knowledge);
            List<Knowledge> tmpList;
            for (Knowledge info : list) {
                tmpList = map.get(info.getTitle());
                if (!CommonUtils.isEmptyOrNull(tmpList) && tmpList.get(0).getTitle().equals(info.getTitle())) {
                    tmpList.add(info);
                    map.put(info.getTitle(), tmpList);
                } else {
                    tmpList = new ArrayList<>();
                    tmpList.add(info);
                    map.put(info.getTitle(), tmpList);
                }
            }
//        }

        result.put(ResponseData.DATA, map);
//			model.addAttribute("list",list);
//        }
        return result;
//		return "knowledge/knowledge_list";

    }


    @RequestMapping("/download/{id}")
    public void download(@PathVariable("id") String id, HttpServletRequest request, HttpServletResponse response) {
        Knowledge knowledge = knowledgeService.getKnowledge(id);
        File file = new File(knowledge.getComment());
        if (file.exists()) {
            InputStream inputStream = null;
            ServletOutputStream outputStream = null;
            try {
                //设置MIME类型
                response.setContentType("application/octet-stream");
                //或者为response.setContentType("application/x-msdownload");
                //设置头信息,设置文件下载时的默认文件名，同时解决中文名乱码问题
                response.addHeader("Content-disposition", "attachment;filename=" + new String(file.getName().getBytes(), "ISO-8859-1"));
                inputStream = new FileInputStream(file);
                outputStream = response.getOutputStream();
                byte[] bs = new byte[1024];
                while ((inputStream.read(bs) > 0)) {
                    outputStream.write(bs);
                }

            } catch (IOException e) {
                log.error("download file error | ", e);
            } finally {
                try {
                    outputStream.flush();
                    outputStream.close();
                    inputStream.close();
                } catch (IOException e) {
                    log.error("download file error | ", e);
                }

            }

        }
    }


}
